import { useMemo } from "react";
import { URLSearchParamsInit, useSearchParams } from "react-router-dom"
import { cleanObject } from "utils";

export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParam] = useSearchParams();
  const setSearchParam = useSetSearchUrlParams()

  return [
    useMemo(
      () => keys.reduce((prev, key) => {
        return {...prev, [key]: searchParam.get(key) || ''}
      }, {} as {[key in K]: string}), 
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [searchParam]
    ),
    (params: Partial<{[key in K]: unknown}>) => {
    
      return setSearchParam(params);
    }
  ] as const;
}

export const useSetSearchUrlParams = () => {
  const [searchParam, setSearchParam] = useSearchParams();

  return (params: {[key in string]: unknown}) => {
    const o = cleanObject({...Object.fromEntries(searchParam), ...params} ) as URLSearchParamsInit
    console.log('clean object res: ', o)
    return setSearchParam(o);
  }
}